{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "301cd562",
   "metadata": {},
   "outputs": [],
   "source": [
    "def f(x):\n",
    "    return x ** 2 - 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "79be84f0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "次数 28 结果 1.41421355959028\n"
     ]
    }
   ],
   "source": [
    "left = 0.5\n",
    "right = 3\n",
    "middle = (left + right) / 2\n",
    "t = 0\n",
    "while True:\n",
    "    if f(middle) > 0:\n",
    "        right = middle\n",
    "    else:\n",
    "        left = middle\n",
    "    middle = (left + right) / 2\n",
    "    t += 1\n",
    "    if abs(left - right) < 0.00000001:\n",
    "        break\n",
    "print (\"次数\",t,\"结果\",middle)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "beaa7255",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
